package org.apache.cassandra.server.impl;

import java.io.File;
import java.io.IOException;

import org.apache.cassandra.server.INodeConfiguration;
import org.apache.cassandra.service.EmbeddedCassandraService;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CassandraNode {

	private Logger logger = LoggerFactory.getLogger(getClass());
	private INodeConfiguration conf;
	private EmbeddedCassandraService cassandra;
	private Thread cassThread;

	public CassandraNode(INodeConfiguration conf) throws TTransportException,
			IOException {
		this.conf = conf;
		logger.info("setting up node with configuration " + conf);
		File confDir = writeStorageXml();
		System.setProperty("storage-config", confDir.getAbsolutePath());
		try {
			setup();
		} catch (Throwable t) {
			logger.error("Could not setup cassandra node", t);
			System.exit(1);
		}
	}

	private File writeStorageXml() {
		File confDir = new File("/var/lib/cassandra/conf/");
		confDir.mkdirs();
		ConfWriter w = new ConfWriter(confDir);
		w.write(conf);
		return confDir;
	}

	private void setup() throws TTransportException, IOException {
		cassandra = new EmbeddedCassandraService();
		cassandra.init();
		cassThread = new Thread(cassandra);
		cassThread.setDaemon(true);
	}

	public void start() {
		logger.info("Node start...");
		new File(conf.getPIDPath()).deleteOnExit();
		cassThread.start();
		logger.info("Node started.");
	}

	public void shutdown() {
		logger.info("shutdown initiated...");
		cassThread.interrupt();
	}

}
